<?php
/**
 * +--------------------------------------------------------+
 * @Created by PhpStorm.
 * @Category StockArticleService.php
 * @Depiction:
 * Author: hwy
 * Date: 2021/2/20  16:53
 * +--------------------------------------------------------+
 */

namespace App\Services;

use App\Jobs\YbsArticleJob;
use App\Models\StockArticle;
use Carbon\Carbon;
use http\Exception;

class StockArticleService extends BaseService
{
    protected $stock_article;

    private $ybs_url = 'https://admin.gbhome.com/api/v4/common/3in1/discovery?pageNum=1&pageSize=10';

    /**
     * StockArticleService constructor.
     * @noinspection PhpMissingParentConstructorInspection
     */
    public function __construct()
    {
        $this->stock_article = new StockArticle();
    }

    public function getList($params)
    {
        $query   = $this->stock_article->query();
        $perPage = $this->perPage($params);

        if (!empty($params['field']) && !empty($params['order'])) {
            $query = $query->orderBy($params['field'], $params['order']);
        }
        if (!empty($params['top'])) {
            $query = $query->where('openStick', $params['top']);
        }
        if (!empty($params['isOpen'])) {
            $isOPen = $params['isOpen'] == 1;
            $query  = $query->where('isOpen', $params['isOpen'] - 1);
        }
        if (!empty($params['category'])) {
            $query = $query->where('zlName', $params['category']);
        }
        if (!empty($params['keyword'])) {
            $query = $query->where('content', 'like', '%' . $params['keyword'] . '%')
                ->orWhere('summary', 'like', '%' . $params['keyword'] . '%')
                ->orWhere('title', 'like', '%' . $params['keyword'] . '%');
        }

        $list = $query
            //            ->orderBy('openStick','desc')
            ->orderBy('created_at', 'desc')
            ->paginate($perPage)
            ->toArray();

        return $list;
    }

    public function getRead($params)
    {
        $data = $this->stock_article->query()->with('has_one_article_stock_content')->where('id', $params)->first();

        return $data;
    }

    /**
     * @param $params
     * @return mixed
     * @Depiction 写入数据
     * @Author hwy
     * @Date 2021/5/27  11:41
     */
    public function addData($params)
    {
        /**
         * es 只用作学习，服务器太小无法支撑
         */
        // $esClient = new ElasticSearchService('ybs_log');
        //
        // foreach ($params as $val) {
        //     $res = $esClient->putDoc($val);
        // }

        return $add = $this->stock_article->insert($params);
    }

    /**
     * @return bool
     * @Depiction 研报社文章采集
     * @Author hwy
     * @Date 2021/5/27  11:32
     */
    public function collectYbsArticle()
    {
        $now    = Carbon::now();
        $hours  = $now->hour;
        $minute = $now->minute;
        if (($hours < 8) || $hours > 15) {
            if ($minute % 30 != 0) {
                return true;
            }
        }

        try {
            $data = curl($this->ybs_url);
        }catch (\Exception $e){
            return false;
        }

        if (empty($data)) {
            return true;
        }
        $list = json_decode($data, true);

        $insert_data = [];

        $db_data_select = $this->stock_article->query()
            ->select('subjectId', 'type')
            ->orderBy('id', 'desc')
            ->limit(20)
            ->get();

        foreach ($list['data']['records'] as $value) {
            //$db_data_select 上面取出了20条，这边不经过数据库，减小数据库压力
            $db_data = $db_data_select->where('subjectId', $value['subjectId'])->where('type', $value['type'])->first();

            if ($db_data) {
                continue;
            }

            $collect_data                    = [];
            $collect_data['title']           = $value['title'];
            $collect_data['created_at']      = $value['createTime'];
            $collect_data['updated_at']      = $value['updateTime'];
            $collect_data['type']            = $value['type'];
            $collect_data['content']         = $value['content'];
            $collect_data['subjectId']       = $value['subjectId'];
            $collect_data['summary']         = $value['summary'];
            $collect_data['readingSum']      = $value['readingSum'];
            $collect_data['commentSum']      = $value['commentSum'];
            $collect_data['cover']           = $value['cover'];
            $collect_data['upTime']          = $value['upTime'];
            $collect_data['isOpen']          = $value['isOpen'];
            $collect_data['openStick']       = $value['openStick'];
            $collect_data['zlAvatarUrl']     = $value['zlAvatarUrl'];
            $collect_data['zlName']          = $value['zlName'];
            $collect_data['zlSubscribeType'] = $value['zlSubscribeType'];
            $collect_data['zlType']          = $value['zlType'];

            $insert_data[] = $collect_data;
        }

        if (!empty($insert_data)) {
            // dispatch((new YbsArticleJob($insert_data))->onQueue('ybs_article'));
            dispatch((new YbsArticleJob($insert_data))->onQueue('default'));
        }
        //获取文章内容
        return true;

    }


    static public function returnWxArticle($title = 'a')
    {

        $app = app('wechat.official_account');

        $openId = 'ogB-LwbqVudImvoN_hyruvh9qcwQ';

        $text = '文章【' . $title . '】';

        $app->broadcasting->previewText($text, $openId);
    }

}
